package monsmon.game.draw;

import monsmon.term.Surface;
import monsmon.term.Terminal;
import monsmon.game.*;
import monsmon.util.TermUtil;

public class GameDraw{
	
	public static final int SQ_SIZE = 5;
	
	private static Surface lstlvl, lstmsg;
	private static int lx = 0, ly = 0;
	
	private static int lpx, lpy, lvlx, lvly;


	public static void draw(Terminal term, MonsGame game){
		Surface cs = term.get_curr_surface();
		if(cs.get_h() != ly || cs.get_w() != lx){
			//Compute surfaces to use
			lx = cs.get_w();
			ly = cs.get_h();
			lvlx = lx * 1 / 2;
			lvly = ly * 7 / 8;
			lstlvl = new Surface(lvlx- 2, lvly - 2);
			lpx = (lx - lvlx) / 2 - 1;
			lpy = (ly - lvly) / 2 - 1;
			lstmsg = new Surface(lpx - 3, lvly);
		}
		lstlvl.clear();
		lstmsg.clear();
		__draw_lvl(lstlvl, game);
		game.msgs.render(lstmsg);
		cs.blit(lstlvl, null, lpx + 1, lpy + 1);
		cs.blit(lstmsg, null , 2, 1);
		TermUtil.box_dr(cs, 1, lpy, lpx, lvly);
		TermUtil.box_dr(cs, lpx + 1, lpy, lvlx, lvly);
		TermUtil.swritef(cs, 5, lpy - 1, "Messages: ");
		TermUtil.swritef(cs, lpx + 5, lpy - 1, "Map: ");
	}

	private static void __draw_lvl(Surface surf, MonsGame game){
		LevelMap lvl = game.get_current_lvl();

		int xl = lvl.get_x_len();
		int yl = lvl.get_y_len();
		//Location of player
		int xp = game.player.get_x();
		int yp = game.player.get_y();

		int ws = surf.get_w();
		int hs = surf.get_h();

		int xsqp = xp / SQ_SIZE - 1;
		int ysqp = yp / SQ_SIZE - 1;
		
		int xoffset = ws / 2 - (xsqp * SQ_SIZE) - xl / 2;
	       	int yoffset = hs / 2 - (ysqp * SQ_SIZE) - xl / 2;

		int xscrl = xoffset;
		int yscrl = yoffset;
		for(int x = 0; x < xl; x++){
			yscrl = yoffset;
			for(int y = 0; y < yl; y++){
				Tile t = lvl.get_tile(x, y);
				if(xscrl >= 0 && xscrl < ws){
					if(yscrl >= 0 && yscrl < hs){	
						__draw_tile(surf, t, xscrl, 
								yscrl);
					}
				}
				yscrl++;
			}
			xscrl++;
		}
	}

	private static void __draw_tile(Surface surf, Tile t, int x, int y){
		if(t == null) return;
		Entity e = t.get_ent();
		if(e == null){
			surf.draw(x, y, t.get_char(), 
					t.get_fg_col(), t.get_bg_col());
		}else{
			surf.draw(x, y, e.get_char(), 
					e.get_fg_col(), e.get_bg_col());
		}
	}
}
